package com.xneure.database;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringUtils;

public enum DataBaseType{
	Oracle("oracle"),MySql("mysql"),SqlServer("sqlserver");
	private String dbName;

	private DataBaseType(String name){
		this.dbName = name;
	}

	public static DataBaseType identify(String identify){
		identify = StringUtils.deleteWhitespace(identify).toLowerCase();
		for(DataBaseType dbt:values()){
			if(identify.contains(dbt.dbName)){
				return dbt;
			}
		}
		return null;
	}

	public static DataBaseType identify(DataSource ds){
		try{
			return identify(ds.getConnection());
		}catch(SQLException e){
			return null;
		}
	}

	public static DataBaseType identify(Connection connection){
		try{
			return identify(connection.getMetaData().getDriverName());
		}catch(SQLException e){
			return null;
		}
	}

	public static DataBaseType identify(DatabaseMetaData metaData){
		try{
			DataBaseType identify = identify(metaData.getDriverName());
			if(null == identify){
				identify(metaData.getClass().getName());
			}
			return identify;
		}catch(SQLException e){
			return null;
		}
	}

	public String getDbName(){
		return dbName;
	}
}
